package com.leyou.pay.service;

import com.alibaba.fastjson.JSON;
import com.alipay.api.AlipayClient;
import com.alipay.api.DefaultAlipayClient;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.leyou.pay.config.AliPayConfig;
import com.leyou.pay.entity.AliPayParam;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.Map;

@Service
@Slf4j
@EnableConfigurationProperties(AliPayConfig.class)
public class AliPayService {

    @Autowired
    private AliPayConfig aliPayConfig;

    public String getHtml(AliPayParam payParam) {

        try {
            //获得初始化的AlipayClient
            AlipayClient alipayClient = new DefaultAlipayClient(
                    aliPayConfig.getGatewayUrl(), aliPayConfig.getAppId(),
                    aliPayConfig.getMerchantPrivateKey(), "json",
                    aliPayConfig.getCharset(), aliPayConfig.getAlipayPublicKey(),
                    aliPayConfig.getSignType());

            //设置请求参数
            AlipayTradePagePayRequest aliPayRequest = new AlipayTradePagePayRequest();
            aliPayRequest.setReturnUrl(aliPayConfig.getReturnUrl());
            aliPayRequest.setNotifyUrl(aliPayConfig.getNotifyUrl());

            Map<String, String> map = new HashMap<>();
            map.put("out_trade_no", payParam.getOutTradeNo());
            map.put("total_amount", payParam.getTotalAmount());
            map.put("subject", payParam.getSubject());
            map.put("body", payParam.getBody());
            map.put("timeout_express", payParam.getTimeoutExpress());
            map.put("product_code", payParam.getProductCode());

            log.info(JSON.toJSONString(map));
            aliPayRequest.setBizContent(JSON.toJSONString(map));

            //请求
            return alipayClient.pageExecute(aliPayRequest).getBody();

        }catch (Exception e){
            log.error("初始化支付宝支付数据错误!");
            e.printStackTrace();
            return null;
        }
    }
}
